import * as express from "express";
import { info } from "./utils/log";
import { RoutesConfig } from "./router";

/**
 * 路由加载启动器
 */
export class Application {
	constructor(public app: express.Express) {}

	/**
	 * 注入全局Express应用实例
	 * @param app Express应用实例
	 * @returns Application
	 */
	static init(app = express()) {
		return new Application(app);
	}

	/**
	 * 引入 websocket 支持
	 * 需要在加载路由之前使用
	 */
	applyWebSocket() {
		require("express-ws")(this.app);
		return this;
	}

	/**
	 * 引入 body-parser 支持
	 * 需要在加载路由之前使用
	 */
	// appBodyParser() {
	// 	this.app.use(bodyParser.urlencoded({ extended: false }));
	// 	this.app.use(bodyParser.json());
	// 	return this;
	// }

	/**
	 *
	 * @param dir 目录名
	 * @returns 开启静态托管
	 */
	applyStatic(dir = "public") {
		this.app.use(express.static(dir));
		return this;
	}

	/**
	 * 加载路由
	 * @param routes 路由注入器类
	 * @returns Application
	 */
	applyRoutes(routes: RoutesConfig | RoutesConfig[]) {
		if (!Array.isArray(routes)) {
			const { path, route } = routes;
			this.app.use(path, route);
		} else {
			routes.forEach(({ path, route }) => this.app.use(path, route));
		}

		return this;
	}

	/**
	 *
	 * @param allow 标识符
	 * @returns 允许跨域请求
	 */
	applyCrossOrigin(allow = true) {
		if (allow) {
			this.app.all("*", function (_req, res, next) {
				res.header("Access-Control-Allow-Origin", "*");
				res.header("Access-Control-Allow-Headers", "X-Requested-With");
				res.header(
					"Access-Control-Allow-Methods",
					"PUT,POST,GET,DELETE,OPTIONS"
				);
				res.header("X-Powered-By", " 3.2.1");
				res.header("Content-Type", "application/json;charset=utf-8");
				next();
			});
		}

		return this;
	}

	/**
	 * 启动服务器
	 * @param port 端口
	 */
	start(port: number | string, callback?: () => Promise<void>) {
		port = Number(port);
		this.app.listen(port, async () => {
			if (callback) {
				await callback();
			}
			info(`Application: http://localhost:${port}`);
		});
	}
}
